using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web;
using CMS.BIZ;
using System.Web.Security;
using System.Web.UI;
using System.Collections.Specialized;
using AjaxControlToolkit;
using FredCK.FCKeditorV2;

namespace CMS.Web.UI.UserControls
{
    public class PageEditor : UserControl
    {

        private BizPage page;
        private BizControl control;

        protected Repeater repeaterPage;

        protected TextBox tbTitle;
        protected TextBox tbName;
        protected TextBox tbMasterPage;
        protected CheckBox cbRequireAuthentication;
        protected DropDownList ddlParent;
        protected Button bValidate;

        protected PlaceHolder phPageEditor;

        protected UpdatePanel upReorderChildren;
        protected ReorderList rlChildren;

        protected UpdatePanel upPageEditorRoles;
        protected ListBox lbRoles;
        protected DropDownList ddlRoles;
        protected Button bAddRole;
        protected Button bRemoveRole;

        protected UpdatePanel upPageEditorContent;
        protected DropDownList ddlCulture;
        protected LinkButton lbCreateContent;
        protected FCKeditor wysiwygEditor;
        protected Button bValidateContent;


        protected UpdatePanel upPageEditorControl;
        protected Repeater repeaterControl;
        protected TextBox tbControlPath;
        protected Button bAddControl;

        public PageEditor()
        {
            base.Init += new EventHandler(PageEditor_Init);
        }

        void PageEditor_Init(object sender, EventArgs e)
        {
            bValidate.Click += new EventHandler(Validate_Click);
            bRemoveRole.Click += new EventHandler(RemoveRole_Click);
            bAddRole.Click += new EventHandler(AddRole_Click);
            lbCreateContent.Click += new EventHandler(CreateContent_Click);
            ddlCulture.SelectedIndexChanged += new EventHandler(Culture_SelectedIndexChanged);
            bValidateContent.Click += new EventHandler(ValidateContent_Click);
            bAddControl.Click += new EventHandler(AddControl_Click);
            rlChildren.ItemReorder += new EventHandler<ReorderListItemReorderEventArgs>(rlChildren_ItemReorder);
            string delete = Request.QueryString["Delete"];
            if (!string.IsNullOrEmpty(delete))
            {
                Page.BizPageProvider.Delete(int.Parse(delete));
            }
            ReadPageFromQueryString();
            ReadControlFromQueryString();
            delete = Request.QueryString["DeleteControl"];
            if (page != null && !string.IsNullOrEmpty(delete))
            {
                Page.BizControlProvider.Delete(int.Parse(delete));
            }
            if (page != null && !Page.IsPostBack)
            {
                // simple inputs
                tbTitle.Text = page.PageTitle;
                tbName.Text = page.PageName;
                tbMasterPage.Text = page.MasterPageFile;
                cbRequireAuthentication.Checked = page.RequireAuthentication;
                if (page.RequireAuthentication) upPageEditorRoles.Visible = true;
                else upPageEditorRoles.Visible = false;
                // ddl roles
                foreach (string role in page.Roles)
                {
                    lbRoles.Items.Add(role);
                }
                if(page.ParentID != null) ddlParent.SelectedValue = page.ParentID.ToString();
                ddlRoles.DataSource = Roles.GetAllRoles();
                ddlRoles.DataBind();
                BindCulture();
                BindControl();
                BindChildren();
                if (control != null)
                {
                    tbControlPath.Text = control.ControlPath;
                    ///TODO bizcontent
                }
                // assign content editor
                SetContentEditor();
            }
            if (page == null)
            {
                phPageEditor.Visible = false;
            }
            else
            {
                phPageEditor.Visible = true;
            }
            if (!IsPostBack)
            {
                BindPage();
            }
        }

        private void BindPage()
        {
            List<BizPage> list = Page.BizPageProvider.GetAll();
            ddlParent.DataSource = list;
            ddlParent.DataTextField = "PageName";
            ddlParent.DataValueField = "PageID";
            ddlParent.DataBind();
            ddlParent.Items.Insert(0, new ListItem("", "", true));
            repeaterPage.DataSource = list;
            repeaterPage.DataBind();
        }

        void rlChildren_ItemReorder(object sender, ReorderListItemReorderEventArgs e)
        {
            SiteMapNodeCollection collection = Page.BizPageProvider.GetChildNodes(page);
            BizPage child;
            List<BizPage> list = new List<BizPage>();
            bool modified = false;
            for (int c = 0; c < collection.Count; c++)
            {
                child = (BizPage)collection[c];
                if (child.PageIndex != c)
                {
                    child.PageIndex = c;
                    Page.BizPageProvider.Update(child);
                }
                list.Add(child);
            }
            child = list[e.OldIndex];
            list.RemoveAt(e.OldIndex);
            list.Insert(e.NewIndex, child);
            for (int c = 0; c < list.Count; c++)
            {
                if (list[c].PageIndex != c)
                {
                    list[c].PageIndex = c;
                    Page.BizPageProvider.Update(list[c]);
                    modified = true;
                }
            }
            if (modified)
            {
                //BindPage();
                BindChildren();
            }
        }

        private void BindChildren()
        {
            if (page != null)
            {
                rlChildren.DataSource = Page.BizPageProvider.GetChildNodes(page);
                rlChildren.DataKeyField = "PageID";
                rlChildren.SortOrderField = "PageIndex";
                rlChildren.DataBind();
            }
        }

        private void ReadControlFromQueryString()
        {
            string controlID = Request.QueryString["ControlID"];
            if (!string.IsNullOrEmpty(controlID))
            {
                control = Page.BizControlProvider.Read(int.Parse(controlID));
            }
        }

        private void BindControl()
        {
            List<BizControl> listControls = Page.BizControlProvider.ReadByPageID(page.PageID);
            repeaterControl.DataSource = listControls;
            repeaterControl.DataBind();
        }

        private void BindCulture()
        {
            // ddl cultures
            List<BizCulture> listCulture = Page.BizCultureProvider.ReadAll("CultureCode");
            ddlCulture.DataSource = listCulture;
            ddlCulture.DataTextField = "CultureName";
            ddlCulture.DataValueField = "CultureCode";
            ddlCulture.DataBind();
            ddlCulture.SelectedValue = Page.CultureCode;
        }

        private void ReadPageFromQueryString()
        {
            string pageId = Request.QueryString["PageID"];
            if (!string.IsNullOrEmpty(pageId))
            {
                page = Page.BizPageProvider.Read(int.Parse(pageId));
            }
        }

        protected void AddControl_Click(object sender, EventArgs e)
        {
            if (page == null) ReadPageFromQueryString();
            if (control == null) ReadControlFromQueryString();
            bool update = true;
            if (control == null)
            {
                update = false;
                control = new BizControl();
                control.PageID = page.PageID;
            }
            control.ControlPath = tbControlPath.Text;
            if (update) Page.BizControlProvider.Update(control);
            else
            {
                Page.BizControlProvider.Create(control);
                BindControl();
            }
        }

        protected void ValidateContent_Click(object sender, EventArgs e)
        {
            if (page == null) ReadPageFromQueryString();
            if (page != null)
            {
                if (page.ContentID != null)
                {
                    BizContent content = Page.BizContentProvider.Find((int)page.ContentID, ddlCulture.SelectedValue);
                    content.ContentText = wysiwygEditor.Value;
                    Page.BizContentProvider.Update(content);
                }

            }

        }

        protected void CreateContent_Click(object sender, EventArgs e)
        {
            if (page == null)
            {
                string pageId = Request.QueryString["PageID"];
                if (!string.IsNullOrEmpty(pageId))
                {
                    page = Page.BizPageProvider.Read(int.Parse(pageId));
                } 
            }
            if (page != null)
            {
                BizContent content = new BizContent();
                if (page.ContentID == null)
                {
                    int nextId = Page.BizContentProvider.GetMaxID() + 1;
                    content.ContentID = nextId;
                    page.ContentID = nextId;
                    Page.BizPageProvider.Update(page);
                }
                else
                {
                    content.ContentID = (int)page.ContentID;
                }
                content.CultureCode = ddlCulture.SelectedValue;
                Page.BizContentProvider.Create(content);
                Response.Redirect(Page.CreateQueryString(Request.QueryString));
            }
        }

        protected void Culture_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetContentEditor();
        }

        private void SetContentEditor()
        {
            if (page.ContentID == null)
            {
                wysiwygEditor.Visible = false;
                bValidateContent.Visible = false;
                lbCreateContent.Visible = true;
                wysiwygEditor.Value = "";
            }
            else
            {
                BizContent content = Page.BizContentProvider.Find((int)page.ContentID, ddlCulture.SelectedValue);
                if (content != null)
                {
                    wysiwygEditor.Visible = true;
                    bValidateContent.Visible = true;
                    lbCreateContent.Visible = false;
                    wysiwygEditor.Value = content.ContentText;
                }
                else
                {
                    wysiwygEditor.Visible = false;
                    bValidateContent.Visible = false;
                    lbCreateContent.Visible = true;
                    wysiwygEditor.Value = "";
                }
            }
        }

        protected void AddRole_Click(object sender, EventArgs e)
        {
            if (page == null) return;
            if (!page.Roles.Contains(ddlRoles.SelectedValue))
            {
                page.Roles.Add(ddlRoles.SelectedValue);
                lbRoles.Items.Add(ddlRoles.SelectedValue);
                Page.BizPageProvider.Update(page);
            }
        }

        protected void RemoveRole_Click(object sender, EventArgs e)
        {
            if (page == null) return;
            List<string> list = new List<string>();
            foreach (ListItem item in lbRoles.Items)
            {
                if(item.Selected) list.Add(item.Value);
            }
            bool changed = false;
            foreach (string role in list)
            {
                if (page.Roles.Contains(role))
                {
                    changed = true;
                    page.Roles.Remove(role);
                    lbRoles.Items.Remove(role);
                }
            }
            if(changed) Page.BizPageProvider.Update(page);
        }

        private bool IsNewPage()
        {
            if (page != null) return false;
            page = new BizPage(Page.BizPageProvider, 0, "", null, "", new List<string>());
            return true;
        }

        protected void Validate_Click(object sender, EventArgs e)
        {
            bool insert = IsNewPage();
            page.MasterPageFile = tbMasterPage.Text;
            page.PageName = tbName.Text;
            page.PageTitle = tbTitle.Text;
            if (ddlParent.SelectedIndex != 0) page.ParentID = int.Parse(ddlParent.SelectedValue);
            else page.ParentID = null;
            page.RequireAuthentication = cbRequireAuthentication.Checked;
            if (insert)
            {
                Page.BizPageProvider.Create(page);
                NameValueCollection collection = new NameValueCollection(Request.QueryString);
                collection["PageID"] = page.PageID.ToString();
                Response.Redirect(Page.CreateQueryString(collection));
            }
            else Page.BizPageProvider.Update(page);
            if (page.RequireAuthentication) upPageEditorRoles.Visible = true;
            else upPageEditorRoles.Visible = false;
        }

    }
}
